package com.offcn.spark.p4

import org.apache.spark.{SparkConf, SparkContext}

import scala.reflect.ClassTag

/**
 * @Auther: BigData-LGW
 * @ClassName: SparkSortSecond
 * @Date: 2020/12/8 21:38
 * @功能描述: $FunctionDescription
 * @Version:1.0
 */
object SparkSortSecond {
    def main(args: Array[String]): Unit = {
        val conf = new SparkConf()
            .setAppName("SparkSortSecond")
            .setMaster("local[2]")
        val sc = new SparkContext(conf)

        val stus = sc.parallelize(List(
            Student("卫超", 19, 187),
            Student("王礼鹏", 29, 177),
            Student("乌欣欣", 18, 168),
            Student("陈延年", 19, 157),
            Student("刘龙沛", 20, 175)
        ))
        //按照年龄升序，如果年龄相同，按照升高进行排序
        println("-------使用sortByKey进行二次排序----------")
        stus.map(stu => (Height(stu.height,stu.age),stu))
                .sortByKey(numPartitions = 1)
                .foreach(kv => println(kv._2))
        println("-------使用sortBy进行二次排序----------")
        stus.sortBy(stu => stu,numPartitions = 1)(
            new Ordering[Student](){
                override def compare(x: Student, y: Student): Int = {
                    var ret = x.age.compareTo(y.age)
                    if(ret == 0){
                        ret = x.height.compareTo(y.height)
                    }
                    ret
                }
            },
            ClassTag.Object.asInstanceOf[ClassTag[Student]]
        ).foreach(println)
        sc.stop()
    }
    case class Student(name: String, age: Int, height: Double)
    case class Height(height: Double,age:Int) extends Ordered[Height]{
        override def compare(that: Height): Int = {
            var ret = age.compareTo(that.age)
            if(ret == 0) {
                ret = height.compareTo(that.height)
            }
            ret
        }
    }
}
